<template>
  <div class="geade" v-loading="loading" element-loading-text="加载中...">
    <div class="header">
      <div style="display: flex; gap: 5px">
        <HPlainButton @click="addLevel"> 添加级别</HPlainButton>
        <el-dropdown trigger="click">
          <HButton :disabled="selecttion.length == 0">
            批量操作
            <el-icon class="el-icon--right">
              <arrow-down />
            </el-icon>
          </HButton>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="changeStatus(1)">
                <el-icon>
                  <CircleCheck />
                </el-icon>
                批量启用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(2)">
                <el-icon>
                  <Warning />
                </el-icon>
                批量禁用
              </el-dropdown-item>
              <el-dropdown-item @click="changeStatus(3)">
                <el-icon>
                  <Delete />
                </el-icon>
                批量删除
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
      <div class="search">
        <el-input v-model="levelInput" placeholder="名称搜索" class="input-with mr5" clearable @keyup.enter="getLevelData"
          @clear="getLevelData" />
        <HButton type="primary" @click="getLevelData">
          <el-icon>
            <Search />
          </el-icon>
          搜索
        </HButton>
      </div>
    </div>
    <div class="table">
      <el-table border stripe resizable :data="levelList" @selection-change="handleChange" ref="levelTable"
        height="100%" style="position: absolute">
        <el-table-column type="selection" width="40" />
        <el-table-column show-overflow-tooltip type="index" label="序号" width="50" />
        <el-table-column show-overflow-tooltip prop="name" label="级别名称" />
        <el-table-column show-overflow-tooltip prop="status" label="状态" width="70">
          <template #default="scope">
            <HStatus v-if="scope.row.status === false">启用</HStatus>
            <HStatus v-if="scope.row.status === true" type="info">禁用</HStatus>
          </template>
        </el-table-column>
        <el-table-column show-overflow-tooltip prop="createTime" label="创建时间" width="170" />
        <el-table-column show-overflow-tooltip prop="updateTime" label="更新时间" width="170" />
        <el-table-column fixed="right" label="操作" width="60">
          <template #default="scope">
            <HLink @click="viewLevelDetail(scope.row)">详细</HLink>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <Pagination ref="levelPaginDom" :list_total="levelTotal" @size-change="getLevelData"
        @current-change="getLevelData" />
    </div>
  </div>

  <!-- 添加/编辑  级别弹窗 -->
  <HModal v-model="addDialog" size="small">
    <template #header>
      <div class="my-header">
        <h3 class="title">{{ levelForm.title }}</h3>
      </div>
    </template>
    <div v-loading="levelLoading" element-loading-text="加载中...">
      <div class="form-text">
        <el-form label-width="80" ref="levelFormRef" :rules="levelRules" :model="levelForm" class="form_content"
          @validate="handleFormValidate">
          <el-form-item label="级别名称" :class="{ form_item: formValidateResult, validate_fail: !formValidateResult }"
            prop="name">
            <el-input v-model="levelForm.name" clearable placeholder="请输入名称" />
          </el-form-item>
          <el-form-item label="级别状态" class="form-item">
            <el-radio-group v-model="levelForm.status" class="el-group">
              <el-radio :value="false">
                <span class="bg_text">启用</span>
              </el-radio>
              <el-radio :value="true">
                <span class="bg_text">禁用</span>
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footerLeft>
      <HPlainBgButton is-modal type="error" v-show="levelForm.title == '编辑级别'" @click="changeStatus(4)">删除
      </HPlainBgButton>
    </template>

    <template #footerRight>
      <HButton is-modal type="primary" @click="saveLevel(levelFormRef)">保存</HButton>
      <HButton is-modal @click="onClose">取消</HButton>
    </template>
  </HModal>
</template>

<script setup lang="ts">
import Pagination from '@/components/Pagination/index.vue'
import { ref, onMounted, reactive, markRaw } from 'vue'
import { Search, Warning, Delete, ArrowDown, CircleCheck } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox, FormItemProp } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { getLevelList, saveUserLevel, changeLevel, deleteLevel } from '@/api/users'
import { Level } from './types'
import HPlainButton from '@/components/common/button/HPlainButton.vue'
import HButton from '@/components/common/button/HButton.vue'
import HPlainBgButton from '@/components/common/button/HPlainBgButton.vue'
import HStatus from '@/components/common/status/HStatus.vue'
import HLink from '@/components/common/link/HLink.vue'
import { HModal } from '@/components/common'

/**
 * 表单验证结果
 */
const formValidateResult = ref(true)

/**
 * 表单验证事件
 */
const handleFormValidate = (prop: FormItemProp, isValid: boolean) => {
  formValidateResult.value = isValid
}

/**
 * 弹窗关闭事件
 */
const onClose = () => {
  addDialog.value = false
  formValidateResult.value = true
}

const levelLoading = ref(false)
const levelList = ref<Array<Level>>([]) // 列表数据
const levelTable = ref() // 列表dom
const levelInput = ref('') // 搜索框
const levelPaginDom = ref<InstanceType<typeof Pagination> | null>(null) // 分页dom
const levelTotal = ref() // 总数目

const loading = ref(false)
const addDialog = ref(false)

const props = defineProps({
  active_name: String,
})

const levelFormRef = ref<FormInstance>() // 表单元素

// 用户级别数据
const levelForm = reactive({
  id: null,
  name: '',
  status: false,
  title: '',
})

// 验证规则
const levelRules = reactive({
  name: [{ required: true, message: '请输入级别名称', trigger: 'blur' }],
})

onMounted(() => {
  if (props.active_name == 'level') {
    getLevelData()
  }
})

// 获取请求的数据
const getData = () => {
  return {
    limit: levelPaginDom.value.size,
    name: levelInput.value,
    page: levelPaginDom.value.current,
    status: '',
  }
}

// 获取级别列表
const getLevelData = async () => {
  loading.value = true
  const res = await getLevelList(getData())
  levelList.value = res.data.data.rows
  levelTotal.value = parseInt(res.data.data.total)
  loading.value = false
}

// 添加级别
const addLevel = () => {
  levelForm.title = '添加级别'
  levelForm.status = false
  levelForm.name = ''
  addDialog.value = true
}

// 修改级别
const viewLevelDetail = (obj: Level) => {
  levelForm.title = '编辑级别'
  levelForm.status = obj.status
  levelForm.name = obj.name
  levelForm.id = obj.id
  addDialog.value = true
}

// 封装保存数据的方法
const saveDataMethod = (method, data, dialog, getData, load) => {
  load.value = true
  method(data).then((res) => {
    if (res.data.success == true) {
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
      dialog.value = false
      load.value = false
      getData()
    } else {
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: 'warning',
          duration: 2000,
        })
      load.value = false
      return
    }
  })
}

// 保存级别数据
const saveLevel = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  const data = {
    id: levelForm.id,
    name: levelForm.name,
    status: levelForm.status,
  }
  formEl.validate((valid) => {
    if (valid) {
      if (levelForm.title == '添加级别') {
        saveDataMethod(saveUserLevel, data, addDialog, getLevelData, levelLoading)
      } else {
        saveDataMethod(saveUserLevel, data, addDialog, getLevelData, levelLoading)
      }
    }
  })
}

// 获取表格选中的数据
const selecttion = ref([])
const handleChange = (val: Array<Level>) => {
  if (val.length != 0) {
    val.forEach((item) => {
      if (Object.values(selecttion.value).indexOf(item.id) === -1) {
        selecttion.value.push(item.id)
      } else {
        selecttion.value = selecttion.value.filter((i) => i === item.id)
      }
    })
  } else {
    selecttion.value = []
  }
}

// 封装修改状态的方法
const changeDisable = (type, method, arr, status, dialog) => {
  if (arr.length == 0) {
    ElMessage({
      message: `请选择要${type}的级别`,
      type: 'warning',
      duration: 2000,
    })
    return
  }
  ElMessageBox({
    type: type == '删除' ? 'error' : 'warning',
    title: '提示',
    icon: type == '删除' ? markRaw(Delete) : markRaw(Warning),
    message: `确认${type}选中的级别?`,
    showCancelButton: true,
    closeOnClickModal: false,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    autofocus: false,
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        instance.confirmButtonLoading = true
        instance.confirmButtonText = '加载中...'
        setTimeout(() => {
          done()
          setTimeout(() => {
            instance.confirmButtonLoading = false
          }, 0)
        }, 1000)
      } else {
        done()
      }
    },
  }).then(async () => {
    if (status != 3) {
      const res = await method(arr, status)
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
    } else {
      const res = await method(arr)
      ElMessage({
        message: res.data.message,
        type: 'success',
        duration: 2000,
      })
      if (dialog == 1) {
        addDialog.value = false
      }
    }
    selecttion.value = []
    levelTable.value.clearSelection()
    getLevelData()
  })
}

// 批量启用/禁用
const changeStatus = (n: 1 | 2 | 3 | 4) => {
  if (n === 1) {
    changeDisable('启用', changeLevel, selecttion.value, false, '')
  }
  if (n === 2) {
    changeDisable('禁用', changeLevel, selecttion.value, true, '')
  }
  if (n === 3) {
    changeDisable('删除', deleteLevel, selecttion.value, 3, '')
  }
  if (n === 4) {
    changeDisable('删除', deleteLevel, [levelForm.id], 3, 1)
  }
}

defineExpose({ getLevelData })
</script>

<style scoped lang="scss">
@import './UserLevel.scss';
@import '../../index.scss';
</style>
